<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd">{{ $t('btn.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="shoppingCart" @click="handleAddCart()" :disabled="!currentRow">加入购物车</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      highlightCurrentRow
      border
      stripe
      @current-change="handleCurrentChange"
      v-dragable="[
        {
          selector: 'thead tr',
          option: {
            animation: 150,
            draggable: '.dragable-col',
            onEnd: (evt) => {
              const startIndex = 0
              const oldIndex = evt.oldIndex - startIndex
              const newIndex = evt.newIndex - startIndex
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex])
                columns.splice(oldIndex + 1, 1)
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex])
                columns.splice(oldIndex, 1)
              }
            }
          }
        }
      ]">
      <template v-for="col in columns">
        <el-table-column
          :key="col['prop']"
          :type="col['type']"
          :prop="col['prop']"
          :label="col['label']"
          :width="col['width']"
          :align="col['align']"
          :min-width="col['min-width']"
          :class-name="col['class-name']"
          :show-overflow-tooltip="col['show-overflow-tooltip']"
          v-if="col['visible']">
          <template #default="scope" v-if="col['custom-template']">
            <component :is="col['custom-template'](scope)"></component>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="600px" appendToBody draggable>
      <el-form ref="formRef" :model="form" labelWidth="120px">
        <el-row>
          <el-col :lg="24">
            <el-form-item label="纪念品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入纪念品名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="纪念品分类" prop="categoryId">
              <el-cascader
                v-model="form.categoryId"
                :options="categoryOptions"
                :props="{
                  emitPath: false,
                  checkStrictly: true,
                  value: 'id',
                  label: 'name',
                  children: 'children'
                }"
                clearable />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="图片" prop="imageId">
              <el-upload
                list-type="picture-card"
                :action="uploadImgUrl"
                :limit="1"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :on-exceed="handleFileExceed"
                :on-success="handleUploadSuccess"
                v-model:file-list="uploadList"
                :headers="headers"
                :data="{ fileNameType: 2, storeType: 1 }"
                :on-preview="handlePictureCardPreview"
                :class="{ hide: uploadList.length >= 1 }">
                <el-icon class="avatar-uploader-icon"><plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="纪念品详情" prop="detail">
              <el-input v-model="form.detail" placeholder="请输入纪念品详情" type="textarea" :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="库存数量" prop="stock">
              <el-input-number v-model="form.stock" placeholder="请输入库存数量" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio-button v-for="item in statusOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

     <el-dialog :title="title" v-model="open1" width="600px" appendToBody draggable>
      <el-form ref="formRef1" :model="form1" labelWidth="120px">
        <el-row>
          <el-col :lg="24">
            <el-form-item label="纪念品名称" prop="name">
              <el-input v-model="form1.name" placeholder="请输入纪念品名称"  disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="纪念品分类" prop="categoryId"  >
              <el-cascader disabled 
                v-model="form1.categoryId"
                :options="categoryOptions"
                :props="{
                  emitPath: false,
                  checkStrictly: true,
                  value: 'id',
                  label: 'name',
                  children: 'children'
                }"
                clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="24">
            <el-form-item label="图片" prop="imageId">
              <el-upload
                list-type="picture-card"
                :action="uploadImgUrl"
                :limit="1"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :on-exceed="handleFileExceed"
                :on-success="handleUploadSuccess"
                v-model:file-list="uploadList"
                :headers="headers"
                :data="{ fileNameType: 2, storeType: 1 }"
                :on-preview="handlePictureCardPreview"
                :class="{ hide: uploadList.length >= 1 }">
                <el-icon class="avatar-uploader-icon"><plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col> -->
          <el-col :lg="24">
            <el-form-item label="纪念品详情" prop="detail">
              <el-input v-model="form1.detail" placeholder="请输入纪念品详情"  disabled type="textarea" :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form1.price" :precision="2" placeholder="请输入价格" disabled/>
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="库存数量" prop="stock">
              <el-input-number v-model="form1.stock" placeholder="请输入库存数量" disabled/>
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form1.status" disabled>
                <el-radio-button v-for="item in statusOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary"  @click="cancel1">{{ $t('btn.cancel') }}</el-button>
        <!-- <el-button type="primary" @click="handleConfirm">{{ $t('btn.submit') }}</el-button> -->
      </template>
    </el-dialog>

    <el-dialog v-model="dialogImageVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { vDragable } from 'element-plus-table-dragable'
import { useI18n } from 'vue-i18n'
import { ElInputNumber, ElMessageBox, FormInstance } from 'element-plus'
import { deepClone, getFormData } from '@/utils'
import modal from '@/plugins/modal'
import { addProduct, deleteProduct, getProductWithPage, updateProduct } from '@/api/souvenir/product'
import { getToken } from '@/utils/auth'
import { getCategoryWithTree } from '@/api/souvenir/category'
import useUserStore from '@/store/modules/user'
import { addCart } from '@/api/souvenir/cart'
const userStore = useUserStore()
const { t } = useI18n()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadImgUrl = ref(baseUrl + import.meta.env.VITE_APP_UPLOAD_URL)
const headers = ref({ Authorization: 'Bearer ' + getToken() })
interface dictOption {
  dictLabel: string
  dictValue: string
}
const statusOptions = ref<dictOption[]>([
  { dictLabel: '在售', dictValue: '1' },
  { dictLabel: '下架', dictValue: '2' }
])
const loading = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
interface product {
  id?: number
  imageUrl: string
  name: string
  detail: string
  price: number
  stock: number
  status: string
  imageId?: number
  categoryId?: number
}
const list = ref<product[]>()
interface column {
  label?: string
  prop?: string
  type?: string
  width?: string
  align?: string
  'min-width'?: string
  'class-name'?: string
  'show-overflow-tooltip'?: boolean
  'custom-template'?: (scope: any) => {}
  visible: boolean
}
const columns = ref<column[]>([
  {
    prop: 'imageUrl',
    label: '图片',
    align: 'center',
    'class-name': 'dragable-col',
    visible: true,
    'custom-template': (scope) => {
      return (
        <>
          <el-image
            preview-teleported
            src={scope.row.imageUrl}
            preview-src-list={[scope.row.imageUrl]}
            hide-on-click-modal
            fit="contain"
            lazy
            class="el-avatar">
            {{
              error: () => {
                return (
                  <>
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </>
                )
              }
            }}
          </el-image>
        </>
      )
    }
  },
  {
    prop: 'name',
    label: '纪念品名称',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'categoryName',
    label: '分类名称',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'detail',
    label: '纪念品详情',
    visible: true,
    'class-name': 'dragable-col'
  },
  {
    prop: 'price',
    label: '价格',
    visible: true,
    'class-name': 'dragable-col',
    'custom-template': (scope) => {
      return <span>￥{scope.row.price}元</span>
    }
  },
  {
    prop: 'stock',
    label: '库存数量',
    visible: true,
    'class-name': 'dragable-col'
  },
  {
    prop: 'status',
    label: '状态',
    visible: true,
    align: 'center',
    'class-name': 'dragable-col',
    'custom-template': (scope) => {
      return (
        <>
          <dict-tag options={statusOptions.value} value={scope.row.status} />
        </>
      )
    }
  },
  {
    prop: 'action',
    label: '操作',
    align: 'center',
    width: '200',
    'custom-template': (scope) => {
      return (
        <>
          <el-button
            text
            icon="edit"
            type="success"
            title={t('btn.edit')}
            onClick={() => {
              handleUpdate(scope.row)
            }}></el-button>
            <el-button
            text
            icon="View"
            type="success"
            title="纪念品详情"
            onClick={() => {
              handleDetail(scope.row)
            }}></el-button>
          <el-button
            text
            icon="delete"
            type="danger"
            title={t('btn.delete')}
            onClick={() => {
              handleDelete(scope.row)
            }}></el-button>
          <el-button
            text
            icon="shoppingCart"
            type="warning"
            title="加入购物车"
            onClick={() => {
              handleAddCart(scope.row)
            }}></el-button>
        </>
      )
    },
    visible: true
  }
])
const title = ref('')
const open = ref(false)
const open1 = ref(false)
const formRef = ref<FormInstance>()
const formRef1 = ref<FormInstance>()
const form = ref<product>({
  name: '',
  detail: '',
  price: 0,
  stock: 0,
  status: '1',
  imageUrl: ''
})
const form1 = ref<product>({
  name: '',
  detail: '',
  price: 0,
  stock: 0,
  status: '1',
  imageUrl: ''
})
const handleUpdate = (row) => {
  title.value = '编辑纪念品'
  open.value = true
  formRef.value?.resetFields()
  reset(true, row)
  formRef.value?.clearValidate()
}

const handleDetail = (row) => {
  title.value = '纪念品详情'
  open1.value = true
  formRef1.value?.resetFields()
  reset1(true, row)
  formRef1.value?.clearValidate()
}

const handleDelete = async (row) => {
  try {
    await modal.confirm('是否要删除?')
    try {
      await deleteProduct(row.id)
      modal.msgSuccess('删除成功')
    } catch (error) {
      console.error(error)
      modal.msgError('删除失败')
    }
    getList()
  } catch (error) {}
}
const handleAdd = () => {
  title.value = '新增纪念品'
  open.value = true
  formRef.value?.resetFields()
  reset(false)
  formRef.value?.clearValidate()
}
const reset = (isUpdate: boolean, row?: any) => {
  uploadList.value = []
  getCategoryOptions()
  if (isUpdate) {
    form.value = deepClone(row)
    if (row?.imageUrl) {
      uploadList.value.push({
        url: row?.imageUrl
      })
    }
  } else {
    form.value = {
      name: '',
      detail: '',
      price: 0,
      stock: 0,
      status: '1',
      imageUrl: ''
    }
  }
}

const reset1 = (isUpdate: boolean, row?: any) => {
  uploadList.value = []
  getCategoryOptions()
  if (isUpdate) {
    form1.value = deepClone(row)
    if (row?.imageUrl) {
      uploadList.value.push({
        url: row?.imageUrl
      })
    }
  } else {
    form1.value = {
      name: '',
      detail: '',
      price: 0,
      stock: 0,
      status: '1',
      imageUrl: ''
    }
  }
}
const cancel1 = () => {
  open1.value = false
  reset1(false)
}
const cancel = () => {
  open.value = false
  reset(false)
}
const handleConfirm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (title.value === '新增纪念品') {
          const { data } = await addProduct(form.value)
          if (data) {
            modal.msgSuccess('新增成功')
          }
        } else {
          const { data } = await updateProduct(form.value)
          if (data) {
            modal.msgSuccess('编辑成功')
          }
        }
      } catch (error) {
        console.error(error)
        if (title.value === '新增纪念品') {
          modal.msgError('新增失败')
        } else {
          modal.msgError('编辑失败')
        }
      }
      open.value = false
      getList()
    }
  })
}
const currentRow = ref()
const handleCurrentChange = (val) => {
  currentRow.value = val
}

// 上传文件列表
const uploadList = ref<any[]>([])
// 上传文件参数
interface uploadData {
  // 文件名称类型
  fileNameType: string | number
  // 文件名称
  fileName: string
  // 文件对象 用于校验
  fileObj: any
}
const uploadData = ref<uploadData>({
  fileNameType: 2,
  fileName: '',
  fileObj: null
})
// 上传文件列表改变钩子
const handleFileChange = (file: any) => {
  uploadData.value.fileObj = file.raw
  // certificationFormModel.value.flag = '1'
}
// 上传文件列表移除钩子
const handleFileRemove = (_file: any) => {
  uploadData.value.fileObj = null
  form.value.imageId = undefined
}
// 上传文件列表超出钩子
const handleFileExceed = (_files: any, _uploadFiles: any) => {
  modal.msgError('超出文件上传数量限制, 请先删除文件列表中的文件, 再重新上传')
}
const dialogImageUrl = ref('')
const dialogImageVisible = ref(false)
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true
}

const handleUploadSuccess = (response) => {
  const { data } = response
  form.value.imageId = data.fileId
}
const categoryOptions = ref([])
const getCategoryOptions = async () => {
  try {
    const { data } = await getCategoryWithTree()
    categoryOptions.value = data
  } catch (error) {}
}

const handleAddCart = async (row?) => {
  try {
    const cartNumberForm = ref({
      quantity: 1,
      productId: 0,
      userId: userStore.userId
    })
    if (row) {
      cartNumberForm.value.productId = row.id
    } else {
      cartNumberForm.value.productId = currentRow.value.id
    }
    const max = row ? row.stock : currentRow.value.stock
    await ElMessageBox({
      title: '系统提示',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      message: () =>
        h('p', [
          h('span', '请输入加入购物车的纪念品数量:'),
          h(ElInputNumber, {
            modelValue: cartNumberForm.value.quantity,
            'onUpdate:modelValue': (value: any) => {
              cartNumberForm.value.quantity = value
            },
            min: 1,
            max: max,
            placeholder: '请输入'
          })
        ])
    })
    try {
      const { data } = await addCart(cartNumberForm.value)
      if (data) {
        modal.msgSuccess('加入购物车成功')
      }
      console.log(cartNumberForm.value)
    } catch (error) {
      modal.msgError('加入购物车失败')
    }
    getList()
  } catch (error) {}
}

const getList = async () => {
  loading.value = true
  try {
    const { data } = await getProductWithPage(queryParams.value)
    list.value = data.result
    total.value = data.totalNum
    loading.value = false
  } catch (error) {
    console.error(error)
    loading.value = false
  }
  loading.value = false
}
getList()
</script>

<style scoped></style>
